package service

import (
	"errors"
	"ollama-go/dto"
	"ollama-go/entity"
	"ollama-go/query"
	"ollama-go/vo"

	"github.com/androidsr/sc-go/model"
	"github.com/androidsr/sc-go/sbuilder"
	"github.com/androidsr/sc-go/sc"
	"github.com/androidsr/sc-go/sgorm"
	"github.com/androidsr/sc-go/sno"
)

var (
	ollamaRolesService *OllamaRolesService
)

type OllamaRolesService struct {
	Roles map[string]string
}

func NewOllamaRolesService() *OllamaRolesService {
	if ollamaRolesService == nil {
		ollamaRolesService = new(OllamaRolesService)
		ollamaRolesService.Roles = make(map[string]string, 0)
	}
	return ollamaRolesService
}

// 使用id获取数据
func (m OllamaRolesService) Get(id string) *vo.OllamaRolesVO {
	data := new(entity.OllamaRoles)
	data.Id = id
	err := sgorm.DB.GetOne(data)
	if err != nil {
		return nil
	}
	return sc.Copy[vo.OllamaRolesVO](data)
}

// 保存数据
func (m OllamaRolesService) Save(dto *dto.OllamaRolesDTO) error {
	exist := sgorm.DB.Exists(entity.OllamaRoles{RoleName: dto.RoleName})
	if exist {
		return errors.New("角色名称已存在")
	}

	dto.Id = sno.GetString()
	entity := sc.Copy[entity.OllamaRoles](dto)
	err := sgorm.DB.Insert(entity)
	return err
}

// 更新数据
func (m OllamaRolesService) UpdateById(dto *dto.OllamaRolesDTO) error {
	dbEntity := new(entity.OllamaRoles)
	dbEntity.Id = dto.Id
	sgorm.DB.GetOne(dbEntity)
	if dbEntity.TenantId != "" && dbEntity.TenantId != dto.TenantId {
		return errors.New("非本人创建不能修改")
	}
	sc.CopyTo(dto, dbEntity)
	delete(m.Roles, dto.Id)
	err := sgorm.DB.UpdateById(dbEntity).Error
	return err
}

// 删除数据
func (m OllamaRolesService) DeleteById(id string) error {
	err := sgorm.DB.DeleteById(entity.OllamaRoles{}, id)
	delete(m.Roles, id)
	return err
}

// 分页列表查询
func (m OllamaRolesService) QueryPage(query *query.OllamaRolesQueryDTO) *model.PageResult {
	sql := `select a.* from ollama_roles a where 1=1 `
	data := make([]vo.OllamaRolesVO, 0)
	b := sbuilder.StructToBuilder(query, sql)
	b.Or().Eq("a.is_open", "1")
	sql, values := b.Build()
	return sgorm.DB.SelectPage(&data, query.BaseQueryDTO.Page, sql, values...)
}

// 分页下拉查询
func (m OllamaRolesService) QueryList(query *model.SelectQueryDTO) *model.PageResult {
	sql := `select a.id as value, a.role_name as label from ollama_roles a where 1=1 `
	data := make([]model.SelectVO, 0)
	b := sbuilder.Builder(sql)
	b.Like("CONCAT(a.id,a.role_name)", query.Label)
	for k, v := range query.Vars {
		b.Eq(k, v)
	}
	b.Multiple().Ors(b.In("a.id", query.Selected))
	b.Or().Eq("a.is_open", "1")
	sql, values := b.Build()
	return sgorm.DB.SelectPage(&data, &query.Page, sql, values...)
}
